package qqclient.service;

import qqcommon.Message;
import qqcommon.MessageType;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

/**
 * @author 王艺锡
 * @version 1.0
 * 该类用于开辟线程，连接服务端，时刻接收服务端发送的消息
 */
public class ClientConnectServerThread extends Thread {
    //该线程需要持有Socket
    private Socket socket;

    @Override
    public void run() {
        while (true) {
            System.out.println("客户端正在等待读取信息...");

            try {
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                Message message = (Message) ois.readObject();

                if (message.getMesType().equals(MessageType.MESSAGE_RET_ONLINE_FRIEND)) {//如果返回的是在线用户信息
                    System.out.println("\n===========当前在线用户列表===========");
                    String[] onlineUsers = message.getContent().split(" ");
                    for (int i = 0; i < onlineUsers.length; i++) {
                        System.out.println("用户 :" + onlineUsers[i]);
                    }

                } else if (message.getMesType().equals(MessageType.MESSAGE_COMM_MES)) {//如果接收到私聊消息
                    System.out.println("\n" + message.getSendTime());
                    System.out.println("\n" + message.getSender() + "对你说:" + message.getContent());
                } else if (message.getMesType().equals(MessageType.MESSAGE_MASS_MES)) {//如果接收到群发消息
                    System.out.println("\n" + message.getSendTime());
                    System.out.println("\n" + message.getSender() + "对大家说 :" + message.getContent());

                } else if (message.getMesType().equals(MessageType.MESSAGE_FILE_MES)) {//如果接收到文件
                    System.out.println("\n提醒:" + message.getSender() + "发送文件给你到:" + message.getDestPath());
                    FileOutputStream fileOutputStream = null;
                    fileOutputStream = new FileOutputStream(message.getDestPath());
                    fileOutputStream.write(message.getFileBytes());

                    if(fileOutputStream != null){
                        fileOutputStream.close();
                        System.out.println("保存文件成功!");
                    }

                } else {
                    System.out.println("暂未开放...");
                }


            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    public ClientConnectServerThread(Socket socket) {
        this.socket = socket;
    }

    public Socket getSocket() {
        return socket;
    }
}
